package my.maven.project.spiderproc.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import my.maven.project.spiderproc.Application;
import my.maven.project.spiderproc.dao.PersonDao;
import my.maven.project.spiderproc.entity.Person;
import my.maven.project.spiderproc.service.IPersonService;
import my.maven.project.spiderproc.service.IWordService;

@Service
public class PersonServiceImpl implements IPersonService {

	private final static Logger LOGGER = LoggerFactory.getLogger(PersonServiceImpl.class);
	
	@Autowired
	private PersonDao personDao;
	@Autowired
	IWordService wordService;
	
	@Override
	public List<Person> getList() {
		return personDao.findAll();
	}

	@Override
	public Person getOne(String Id) {
		return personDao.getOne(Id);
	}

	@Transactional(propagation=Propagation.REQUIRED)
	@Override
	public void add(Person entity) {
		personDao.save(entity);
	}
 
	@Override
	public void delete(String Id) {
		personDao.delete(Id);
	}

	@Override
	public boolean update(Person entity) {
		Person p = personDao.getOne(entity.getId());
		if(p != null)
		{
			 p.setAge(entity.getAge());
			 p.setName(entity.getName());
			 p.setCreateDate(new Date());
			 personDao.save(p);
			 return true;
		}
		return false;
	}

	@Transactional(propagation=Propagation.REQUIRED)
	@Override
	public void addList(List<Person> list) {
		for (Person entity : list) {
			personDao.save(entity);
		}
	}
	
	/**
	 * 在springboot中，使用事务回滚时，添加@Transactional注解。
	 * 1：手动抛出一个异常： throw new RuntimeException();
	 * 2: 通过方法回滚：TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); 
	 */
	@Transactional(propagation=Propagation.REQUIRED)
	public void addNewPersonWord(Person entity) throws Exception
	{
		add(entity);
		
		String[] words = new String[] {entity.getName()}; 
		List<String> list = Arrays.asList(words); 
		wordService.SpiderList(list);	
		
//		throw new RuntimeException("手动抛出异常，回滚事务。");
//		TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); 
//		LOGGER.debug("手动抛出异常，回滚事务。");
	}

}
